<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="success" @click="handleCreate">&emsp;新增&emsp;</el-button>
          <el-button type="danger" @click="handleDeleteAll">批量删除</el-button>
          <el-form ref="listQuery" :inline="true"
                   :model="listQuery" class="demo-form-inline"
          >
            <el-form-item label="">
              <el-select v-model="listQuery.display" clearable
                         filterable placeholder="请选择状态"
              >
                <el-option v-for="item in displayOptions" :key="item.value"
                           :label="item.label" :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="listQuery.keyword" clearable
                        placeholder="请输入名称" type="text"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchSubmit">查询</el-button>
              <el-button type="primary" @click="resetSubmit">重置</el-button>
            </el-form-item>
          </el-form>
        </el-row>
      </div>
      <div v-loading="listLoading" class="item">
        <el-table ref="dataList"
                  :data="menuList" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                  border row-key="id" style="width:100%;margin-bottom: 20px;"
                  @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="名称" prop="title"></el-table-column>
          <el-table-column label="图片" min-width="100px" prop="content">
            <template slot-scope="scope">
              <el-popover max-width="220px" placement="right" trigger="hover">
                <img :src="scope.row.content" alt="" style="max-width: 200px"/>
                <img slot="reference" :src="scope.row.content" alt=""
                     style="width: 100px"
                />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="额外展示位" prop="category_name"></el-table-column>
          <el-table-column label="展示URL" prop="link_url"></el-table-column>
          <el-table-column label="排序" prop="sort"></el-table-column>
          <el-table-column label="开始时间" prop="start_time"></el-table-column>
          <el-table-column label="结束时间" prop="end_time"></el-table-column>
          <el-table-column label="状态" prop="display">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.display === 0" type="danger">隐藏</el-tag>
              <el-tag v-if="scope.row.display === 1" type="success">显示</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="260px">
            <template slot-scope="scope">
              <el-button icon="el-icon-edit" plain size="mini"
                         type="primary" @click="handleUpdate(scope.row)"
              >编辑
              </el-button>
              <el-button icon="el-icon-delete" plain
                         size="mini" type="danger" @click="handleDelete(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination :limit.sync="listQuery.perPage" :page.sync="listQuery.page" :total="total"
                        @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog :visible.sync="deleteDialogVisible" title="确定删除吗?" width="435px">
      <span><em style="font-style:normal;color:red">删除后不可恢复</em>，你还要继续吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增编辑弹框 -->
    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]"
               :visible.sync="dialogFormVisible"
               @close="handleCloseDialog('editRulesForm')"
    >
      <el-form ref="editRulesForm" :model="editRulesForm"
               :rules="editRulesFormRules" class="demo-ruleForm" label-width="120px"
      >
        <el-form-item label="轮播图名称" prop="title">
          <el-input v-model="editRulesForm.title" clearable
                    placeholder="请输入名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="轮播图图片" prop="content">
          <el-upload

            :http-request="customizeUpload"
            :on-success="handleSuccess"
            :show-file-list="false"
            action=""
            class="avatar-uploader"
          >
            <img v-if="editRulesForm.content"
                 :src="editRulesForm.content"
                 class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情图">
          <el-upload

            :http-request="customizeUpload"
            :on-success="handleSuccess1"
            :show-file-list="false"
            action=""
            class="avatar-uploader"
          >
            <img v-if="editRulesForm.detail_pictures" :src="editRulesForm.detail_pictures" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="轮播图类型" prop="type">
          <el-select v-model="editRulesForm.type" clearable
                     filterable placeholder="请选择类型"
                     @change="handleChangeType"
          >
            <el-option v-for="item in adType"
                       :key="item.value" :label="item.label"
                       :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="位置" prop="category_id">
          <el-radio
            v-for="item in options"
            :key="item.id"
            v-model="editRulesForm.category_id"
            :label="item.id"
            @change="radioClick(item)"
          >
            {{ item.title }}
          </el-radio>
        </el-form-item>
        <el-form-item
          v-if="[3, 4, 5].includes(editRulesForm.category_id)"
          prop="skip_target"
        >
          <el-select v-model="editRulesForm.skip_target" placeholder="请选择">
            <el-option
              v-for="item in skippArr"
              :key="item.val"
              :label="item.tagged"
              :value="item.val"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="editRulesForm.type === 1" label="房间ID">
          <el-input v-model="editRulesForm.item_id" placeholder="请输入房间ID"/>
        </el-form-item>
        <el-form-item v-if="editRulesForm.type === 3" label="外部链接">
          <el-input v-model="editRulesForm.link_url" placeholder="请输入外部链接"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="editRulesForm.sort" placeholder="请输入排序"/>
        </el-form-item>
        <el-form-item label="状态" prop="display">
          <el-radio-group v-model="editRulesForm.display">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开始-结束时间" prop="value1">
          <el-date-picker
            v-model="editRulesForm.value1"
            end-placeholder="结束日期"
            range-separator="至"
            start-placeholder="开始日期"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { deleteData, getListAdCategory, listData, postAddData, putEditData } from '@/api/content/listAD'

export default {
  data() {
    return {

      // confirmBtn: false,
      giveShowDetailPicture: [],
      giveShowPicture: [],
      // token值

      displayOptions: [
        { value: 0, label: '隐藏' },
        { value: 1, label: '显示' }
      ],
      adType: [
        { value: 1, label: '房间' },
        { value: 3, label: '外部链接' },
        { value: 5, label: 'H5' },
        { value: 8, label: '商城上新推荐' },
        { value: 6, label: '无操作' }
      ],
      // 要修改的当前行的idsearchSubmit
      row_id: 0,
      // 表单规则
      editRulesFormRules: {
        title: [
          {
            required: true,
            message: '请输入名称1-30字符',
            trigger: 'blur',
            min: 1,
            max: 30
          }
        ],
        content: [{ required: true, message: '请选择图片', trigger: 'change' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        display: [{ required: true, message: '请选择状态', trigger: 'change' }],
        value1: [{ required: true, message: '请选择开始时间-结束时间', trigger: 'blur' }],
        category_id: [
          { required: true, message: '请选择位置', trigger: 'change' }
        ]
      },
      editRulesForm: {
        title: undefined,
        item_id: undefined,
        link_url: '',
        display: 1,
        sort: undefined,
        type: undefined,
        content: undefined,
        detail_pictures: undefined,
        category_id: undefined,
        value1: [],
        skip_target: undefined
      },
      dialogStatus: '',
      // dialog的头部信息
      titleMap: {
        update: '编辑',
        create: '新增'
      },
      dialogFormVisible: false,
      deleteDialogVisible: false,
      listLoading: false,
      menuList: [],
      limitList: [],
      listQuery: {
        page: 1,
        perPage: 10,
        keyword: undefined,
        display: undefined
      },
      total: 0,
      // 勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: '',
      options: [],
      skippArr: []
    }
  },
  created() {
    this.getList()
    this.getListAdCategory()
    // this.getBannerSkip()
  },
  methods: {
    radioClick(item) {
      console.log(this.editRulesForm.category_id)
      if (item.is_have === 1) {
        this.$confirm(`${item.title}位置已存在${item.is_have_name}`, '是否替换?', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).then(() => {
        })
          .catch(() => {
            this.editRulesForm.category_id = null
          })
      }
    },
    async getListAdCategory() {
      const { data } = await getListAdCategory()
      this.options = data
      this.options.unshift({ id: -1, title: '无', status: 0 })
    },
    // async getBannerSkip() {
    //   const {data} = await getBannerSkip()
    //   this.skippArr = data
    // },
    getList() {
      this.listLoading = true
      let urlData = '?'
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`
      }
      if (this.listQuery.display === 0 || this.listQuery.display === 1) {
        urlData = urlData + `&display=${this.listQuery.display}`
      }
      if (this.listQuery.keyword) {
        urlData = urlData + `&keyword=${this.listQuery.keyword}`
      }

      listData(urlData).then(response => {
        this.menuList = response.data.list
        this.total = response.data.meta.total
        this.listLoading = false
        // this.confirmBtn = false
      })
    },
    searchSubmit() {
      this.listQuery.page = 1
      this.getList()
    },
    // 点击重置
    resetSubmit() {
      this.listQuery.page = 1
      this.listQuery.perpage = 10
      this.listQuery.display = undefined
      this.listQuery.keyword = undefined
    },
    // 图片上传
    handleRemove(file, fileList) {
      // document.querySelector('.el-upload1 .el-upload').style = 'display:block'
      this.editRulesForm.content = ''
      this.giveShowPicture = []
    },
    handleSuccess() {
      this.editRulesForm.content = this.ossLastImgUrl
    },
    handleSuccess1() {
      this.editRulesForm.detail_pictures = this.ossLastImgUrl
    },
    handleChangeType() {
      this.editRulesForm.item_id = undefined
      this.editRulesForm.link_url = ''
    },
    // 点击新增
    handleCreate() {
      this.resetForm('editRulesForm')
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 点击编辑
    handleUpdate(row) {
      this.row_id = row.id
      this.editRulesForm.title = row.title
      this.editRulesForm.item_id = row.item_id
      this.editRulesForm.link_url = row.link_url || ''
      this.editRulesForm.display = row.display
      this.editRulesForm.sort = row.sort
      this.editRulesForm.type = row.type
      this.editRulesForm.content = row.content
      if (row.category_id === 0) {
        this.editRulesForm.category_id = -1
      } else {
        this.editRulesForm.category_id = row.category_id
      }
      if (this.editRulesForm.category_id === 4 || this.editRulesForm.category_id === 5) this.editRulesForm.skip_target = row.skip_target
      this.editRulesForm.value1 = []
      this.editRulesForm.value1[0] = new Date(row.start_time)
      this.editRulesForm.value1[1] = new Date(row.end_time)
      this.giveShowPicture = [{ url: row.content }]
      if (row.detail_pictures) {
        this.editRulesForm.detail_pictures = row.detail_pictures
        this.giveShowDetailPicture = [{ url: row.detail_pictures }]
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    handleCloseDialog(formName) {
      this.editRulesForm.content = ''
      this.editRulesForm.detail_pictures = ''
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate() // 清除整个表单的校验
      }
    },

    // 重置表单内容
    resetForm(formName) {
      this.$nextTick(() => {
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields()
        }
        this.cityList = []
        this.editRulesForm = {
          title: undefined,
          item_id: undefined,
          link_url: '',
          display: 1,
          sort: undefined,
          type: undefined,
          content: undefined,
          detail_pictures: undefined,
          category_id: undefined
        }
      })
    },
    submitForm(formName) {

      this.$refs[formName].validate(valid => {
        if (valid) {
          this.editRulesForm.start_time = new Date(this.editRulesForm.value1[0]).getTime()
          this.editRulesForm.end_time = new Date(this.editRulesForm.value1[1]).getTime()
          if (this.dialogStatus === 'create') {
            this.editRulesForm.display = this.editRulesForm.display.toString()
            let obj = {}
            if (this.editRulesForm.category_id !== 4 && this.editRulesForm.category_id !== 5) this.editRulesForm.skip_target = undefined
            for (let key in this.editRulesForm) {
              if (this.editRulesForm[key] !== undefined && this.editRulesForm[key] !== '') {
                obj[key] = this.editRulesForm[key]
              }
            }
            obj.display = parseInt(obj.display)
            obj.sort = parseInt(obj.sort)
            delete obj.value1
            postAddData(obj).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              }
            })
          } else {
            this.editRulesForm.display = this.editRulesForm.display.toString()
            let obj = {}
            if (this.editRulesForm.category_id !== 4 && this.editRulesForm.category_id !== 5) this.editRulesForm.skip_target = undefined
            for (let key in this.editRulesForm) {
              if (this.editRulesForm[key] !== undefined && this.editRulesForm[key] !== '') {
                obj[key] = this.editRulesForm[key]
              }
            }
            obj.display = parseInt(obj.display)
            obj.sort = parseInt(obj.sort)
            delete obj.value1
            putEditData(this.row_id, obj).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = { ids: `${row.id}` }
      this.deleteDialogVisible = true
    },
    // 点击批量删除
    handleDeleteAll() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请先勾选要删除的内容',
          type: 'warning'
        })
        return
      } else if (this.multipleSelection.length !== 0) {
        let ids = ''
        for (let key in this.multipleSelection) {
          ids += `${this.multipleSelection[key].id},`
        }
        ids = ids.substring(0, ids.length - 1)
        this.dataIds = { ids: ids }
      }
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {
      this.deleteDialogVisible = false
      deleteData(this.dataIds).then(response => {
        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        }
      })
    }
  }
}
</script>

<style scoped>
[v-cloak] {
  display : none;
}

.clearfix:before,
.clearfix:after {
  display : table;
  content : "";
}

.clearfix:after {
  clear : both;
}

.box-card {
  width : 100%;
}

.demo-form-inline {
  float : right;
}

/deep/ .el-card__header {
  padding-bottom : 0;
}

::v-deep .el-upload-list__item {
  transition : none !important;
}

::v-deep.avatar-uploader .el-upload {
  border        : 1px dashed #d9d9d9;
  border-radius : 6px;
  cursor        : pointer;
  position      : relative;
  overflow      : hidden;
}

.avatar-uploader .el-upload:hover {
  border-color : #409eff;
}

.avatar-uploader-icon {
  font-size   : 28px;
  color       : #8c939d;
  width       : 100px;
  height      : 100px;
  line-height : 100px;
  text-align  : center;
}

.avatar {
  width   : 100px;
  height  : 100px;
  display : block;
}
</style>
